<?php
/**
 * @package es2reveng
 * @name ES2 .BIN string viewer
 * @author marco 'harddisk' schuster
 * @license GPL v3
 */
require 'helpers.php';
$f = $argv[1];
if(isset($argv[2]))
	$m=(int)$argv[2];
else
	$m=-1;
echo "viewing file $f\n";
if (!is_file($f))
	die("file broken");
$fp = fopen($f, "rb");
$type = strtolower(pathinfo($f, PATHINFO_EXTENSION));

//get headerlength
$offset = -1; //the ++ incrementor will read at byte 1 if this is omitted
$b1 = getchar($fp, ++$offset, false);
$b2 = getchar($fp, ++$offset, false);
$b3 = getchar($fp, ++$offset, false);
$b4 = getchar($fp, ++$offset, false);
$hdrlen = le_to_int($b1, $b2,$b3,$b4);
//get payload length
$b1 = getchar($fp, ++$offset, false);
$b2 = getchar($fp, ++$offset, false);
$b3 = getchar($fp, ++$offset, false);
$b4 = getchar($fp, ++$offset, false);
$paylen = le_to_int($b1, $b2,$b3,$b4);

echo "header is $hdrlen bytes long, payload $paylen bytes\n";
if (2*$hdrlen + $paylen + 8 != filesize($f))//header length is 2*N because header is composed of WORDs
	echo "warning: file size in header (".(2*$hdrlen + $paylen + 8)." bytes) differs from actual file size (".filesize($f)." bytes).\nthis file may contain strange messages.\n";


//get header
for ($i = 0; $i < $hdrlen; $i++) {
	//echo "begin reading at offset ".dechex($offset)."\n";
	$ml = getchar($fp, ++$offset, false);
	$mh = getchar($fp, ++$offset, false);
	$msg_offset = le_to_int($ml, $mh);
	//echo "message $i starts at offset $msg_offset\n";
	$messages[$i]["offset"]=$msg_offset;
}

// get messages
for($i=0;$i<sizeof($messages);$i++) {
	$offset=8+($hdrlen*2)+$messages[$i]["offset"]-1;//-1 because of getchar prefix increment
	$byte=getchar($fp,++$offset);
	while($byte!="\0") {
		$messages[$i]["text"].=$byte;
		$byte=getchar($fp,++$offset);
	}
}
if ($offset != filesize($f))
	echo "arrived at structural end (offset is $offset, flen is ".filesize($f)."), but there are still some bytes left\n";
else
	echo "file parse OK\n";

if($m==-1)
	print_r($messages);
else
	echo "target msg $m is ".$messages[$m]["text"]."\n";
?>